import java.io.InputStream;
import java.io.InputStreamReader;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.Sprite;
import javax.microedition.media.*;
import org.json.me.JSONArray;
import org.json.me.JSONObject;

public class mPlayer extends Canvas implements CommandListener,Runnable,PlayerListener {
    private Player player;
    private Song[] songs;
    private Playlist playlist;
    private int curIndex;
    private Image imgPlayer, logoImg, imgPlay;
    private Command CMD_BACK;
    private boolean isLoaded = false, isPlaying=false, isStop;
    private Thread gauge;
    private int total, played;
    
    public mPlayer() {
        CMD_BACK = new Command("Back",Command.BACK,0);
        this.addCommand(CMD_BACK);
        this.setCommandListener(this);
        gauge = new Thread(this);
        gauge.start();
        total=0;
        played=0;
        imgPlayer = null;
        try{
            imgPlayer = Image.createImage("/player.png");
            logoImg = Image.createImage("/logo.png");
            imgPlay = Image.createImage("/play.png");
        } catch (Exception ex){}
    }
    public void load(Song song){
        playStop();
        this.songs = null;
        this.songs = new Song[1];
        this.songs[0] = song;
        this.playlist=null;
        curIndex = 0;
        isLoaded=true;
    }
    public void load(Playlist playlist){
        playStop();
        songs=null;
        this.playlist = null;
        this.playlist = playlist;
        try {
            HttpConnection hc = (HttpConnection)Connector.open(AppManager.SERVER+"songinplaylist.php?plid="+playlist.code);
            InputStream is = hc.openInputStream();
            InputStreamReader isr = new InputStreamReader(is,"utf-8");
            char[] data = new char[1];
            String str_json ="";
            while (isr.read(data)!=-1){
                str_json += new String(data);
            }
            JSONArray ja = new JSONArray(str_json);
            this.songs = new Song[ja.length()-1];
            JSONObject jo;
            for (int i=0; i<ja.length()-1; i++){
                jo = ja.getJSONObject(i);
                this.songs[i] = new Song(jo.getString("spl_id"),jo.getString("spl_name"),jo.getString("casi_name"),0,jo.getString("url"));
            }
            isLoaded=true;
        } catch (Exception ex){}
        this.curIndex = 0;
    }
    
    public void playStart(){
        try {
            player = Manager.createPlayer(songs[curIndex].url);
            player.addPlayerListener(this);
            player.realize();
            player.prefetch();
            total=(int)(player.getDuration()/1000000);
            played=0;
            player.start();
            isPlaying = true;
            isStop=false;
        } catch (Exception ex){}
    }
    public void playIndex(int index){
        try {
            playStop();
            curIndex = index;
            playStart();
        } catch (Exception ex){}
    }
    public void playNext(){
        if (songs.length>1){
            playStop();
            curIndex++;
            curIndex= curIndex>=songs.length?0:curIndex;
            playStart();
        }
    }
    public void playBack(){
        if (songs.length>1){
            playStop();
            curIndex--;
            curIndex= curIndex<0?songs.length-1:curIndex;
            playStart();
        }
    }
    public void playPause(){
        try{
            player.stop();
            isPlaying = false;
        }catch(Exception ex){}
    }
    public void playCont(){
        try{
            if (isStop){
                playStart();
                isStop=false;
            } else {
                player.start();
                isPlaying = true;
            }
        } catch (Exception ex){}
    }
    public void playStop(){
        if (isLoaded){
            player.close();
            total=0;
            played=0;
            isPlaying=false;
            isStop=true;
        }
    }
    protected void paint(Graphics g) {
        g.setColor(0x000000);
        g.fillRect(0, 0, this.getWidth(), this.getHeight());
        g.setColor(0xEFEFEF);
        Font f = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_LARGE);
        g.setFont(f);
        g.drawString(songs[curIndex].name, getWidth()/2, 50, Graphics.BASELINE | Graphics.HCENTER);
        f = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_LARGE);
        g.setFont(f);
        g.drawString("Artis: "+songs[curIndex].artis, getWidth()/2, 70, Graphics.BASELINE | Graphics.HCENTER);
        if (playlist != null){
            g.drawString("Playlist: "+ playlist.name, getWidth()/2, 90, Graphics.BASELINE | Graphics.HCENTER);
        }
        g.fillRect(10, 120, getWidth()-20, 5);
        g.drawString((played/60)+":"+(played%60), 10, 125, Graphics.TOP | Graphics.LEFT);
        g.drawString((total/60)+":"+(total%60), getWidth()-10, 125, Graphics.TOP | Graphics.RIGHT);
        g.setColor(0xFF0000);
        g.fillRect(10, 120, (int)((getWidth()-20)*((float)played/(float)total)), 5);
        g.drawRegion(imgPlayer, 0, 0, 96, 96, Sprite.TRANS_NONE, this.getWidth()/2, 240, Graphics.VCENTER | Graphics.HCENTER);
        if (isStop || !isPlaying){
            g.drawImage(imgPlay, getWidth()/2, 240, Graphics.VCENTER | Graphics.HCENTER);
        }
        g.drawImage(logoImg, getWidth()/2, 160, Graphics.VCENTER | Graphics.HCENTER);
    }
    
    protected void keyPressed(int keyCode) {
        if (getKeyName(keyCode).equals("Down") && songs.length>1){
            f_readsong frm = new f_readsong(2);
            frm.load(songs);
            frm.setPlaylist(playlist);
            frm.title = "Song in-"+playlist.name;
            AppManager.open(frm);
        } else if (getKeyName(keyCode).equals("Left")){
            playBack();
        } else if (getKeyName(keyCode).equals("Right")){
            playNext();
        } else if (getKeyName(keyCode).equals("Select")){
            if (isPlaying) {
                playPause();
            } else {
                playCont();
            }
            repaint();
        } else if (getKeyName(keyCode).equals("Up")){
            playStop();
        }
    }

    public void commandAction(Command c, Displayable d) {
        if (c==CMD_BACK) {
            AppManager.back();
        }
    }

    public void run() {
        while (true){
            if ((!isStop) && isPlaying){
                played=(int)(player.getMediaTime()/1000000);
                repaint();
            }
            try {Thread.sleep(1000);} catch (Exception ex){}
        }
    }

    public void playerUpdate(Player player, String event, Object eventData) {
        if (event.equals("endOfMedia")) playNext();
        }
    }
